<?php

namespace App\Models;

use Dcat\Admin\Layout\Content;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Dcat\Admin\Widgets\Alert;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;

class TryMessage extends Model
{
    use HasDateTimeFormatter;
    protected $table = 'try_message';
    protected $fillable = ['sex', 'open_id', 'age', 'city', 'occ', 'money', 'live', 'label', 'uuid', 'img', 'evaluate', 'name', 'address', 'phone','eat_type', 'remarks','head_img','nick_name','recommend','status'];

    public function update(array $attributes = [], array $options = [])
    {

        if ($this->status == 1 && $this->status_te == 0 && $this->examine == 0) {
            //todo  发送模板
            $data = [];
            if ($this->deliver == 1 && $this->status ==1) {
                $data['thing1']['value'] = 'AMX共创官招募活动';
                $data['thing2']['value'] = '快来填写反馈问卷～';
                $data['thing3']['value'] = '有机会领取AMX系列镭射包！';
                $template = [
                    'te_data'=>$data,
                    'template_id'=>'RlDAQmbXiT4UwuH178pc8oJ0k4CTMfGL_LIQaapMpwM',
                    'open_id'=>$this->open_id,
                    'page'=>'/packageDESIGN/pages/index/index'
                ];
                self::SendMessage($template);
            }

        }
        return parent::update($attributes, $options); // TODO: Change the autogenerated stub
    }


    public function getImgAttribute()
    {
        return $this->attributes['img']?explode(",",$this->attributes['img']):$this->attributes['img'];
    }
    public function SendMessage($template)
    {
        $token = env('WX_TOKEN');
        $client = new Client(['', 'timeout' => 5.0,]);
        //拿到微信access_token
        $response1 = $client->get('https://amxshop.yili.com/api/user/getAccessToken', ['headers' => ['accessToken' => $token]]);
        $data = json_decode($response1->getBody()->getContents());
        $wx_token = $data->data;
        \App\Jobs\WxMessage::dispatch($template, $wx_token, $client);


    }

    public function wxMessage($open_id)
    {
        $data['thing1']['value'] = 'AMX共创官招募活动';
        $data['thing2']['value'] = '恭喜您成为共创官～';
        $data['thing3']['value'] = '点击填写地址，快领取绝密新品吧～';
        $template = [
            'te_data'=>$data,
            'template_id'=>'RlDAQmbXiT4UwuH178pc8oJ0k4CTMfGL_LIQaapMpwM',
            'open_id'=>$open_id,
            'page'=>'/packageDESIGN/pages/index/index'
        ];
        self::SendMessage($template);
    }

}
